/**
 The MIT License

Copyright (c) <2011> <JPACHUBE Team>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
 */
package com.pachube.commons.impl;

import java.awt.Color;
import java.net.URL;
import java.util.ArrayList;

import com.pachube.api.Data;
import com.pachube.api.Feed;
import com.pachube.api.Location;
import com.pachube.api.Pachube;
import com.pachube.api.Status;
import com.pachube.exceptions.PachubeException;

/**
 * The Class Feed.
 */
public class FeedImpl implements Feed {

    /** Gateway to the pachube service. */
    private Pachube p;

    /** id of the feed. */
    private Integer id;

    /** Title of the feed. */
    private String title;

    /** Last time the feed was updated. */
    private String updated;

    /** Url of the feed. */
    private URL feed;

    /** Wheather the feed is live or frozen. */
    private Status status;

    /** A description of this feed. */
    private String description;

    /** Url of a Website which is related to this feed. */
    private URL website;

    /** Publicly available email address. */
    private String email;

    /** Details of the Location of the feed source. */
    private Location location;

    /** Collection of Data object which represent the datastreams of this feed. */
    private ArrayList<Data> data;

    /**
     * Wheather the feed has been created by the PachubeFactory. This variable
     * should not be changed by users
     */
    private boolean Created = false;

    /**
     * Constructor.
     * 
     * @param p Pachube object which is used to authenticate user when updating
     *            this feed
     */
    public FeedImpl(Pachube p) {
        this.p = p;
        this.data = new ArrayList<Data>();

    }

    /**
     * Instantiates a new feed.
     */
    public FeedImpl() {
        // TODO Auto-generated constructor stub
    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Feed#createDatastream(Pachube.Data)
     */
    public void createDatastream(Data d) throws PachubeException {
        if (this.p != null) {
            if (this.p.createDatastream(this.id, d.toXMLWithWrapper())) {
                this.data.add(d);
            }

        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Feed#deleteDatastream(int)
     */
    public void deleteDatastream(int id) {
        if (this.p != null) {
            this.p.deleteDatastream(this.id, id);
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Feed#updateDatastream(int, java.lang.Double)
     */
    public void updateDatastream(int id, Double value) {
        if (this.p != null) {
            Data d = this.lookup(id);
            if (d != null) {
                d.setValue(value);
                this.p.updateDatastream(this.id, id, d.toXMLWithWrapper());
            }
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Feed#updateDatastream(com.pachube.api.Data)
     */
    public void updateDatastream(Data da) {
        if (this.p != null) {
            if (da != null) {

                this.p.updateDatastream(this.id, lookup(da.getId()).getId(),
                        da.toXMLWithWrapper());
            }
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Feed#getDatastream(int)
     */
    public Double getDatastream(int id) {
        return lookup(id).getValue();
    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Feed#getDatastreamHistory(int)
     */
    public Double[] getDatastreamHistory(int id) {
        if (this.p != null) {
            return this.p.getDatastreamHistory(this.id, id);
        }
        return null;
    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Feed#getDatastreamArchive(int)
     */
    public String[] getDatastreamArchive(int id) {
        if (this.p != null) {
            return this.p.getDatastreamArchive(this.id, id);
        }
        return null;
    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Feed#getGraph(int, int, int, java.awt.Color)
     */
    public String getGraph(int id, int width, int height, Color c) {
        if (this.p != null) {
            return this.p.showGraph(this.id, id, width, height, c);
        }
        return null;
    }

    /**
     * Gets a Data object from the internal collection.
     * 
     * @param id id of the Data object to get
     * @return the data
     */
    private Data lookup(int id) {
        for (int i = 0; i < this.data.size(); i++) {
            if (this.data.get(i).getId() == id) {
                return this.data.get(i);
            }
        }
        return null;
    }

    /**
     * Submits the data to pachube.
     * 
     * @throws PachubeException the pachube exception
     */
    private void update() throws PachubeException {
        if (this.p != null) {
            if (this.Created) {
                this.p.updateFeed(this.id, this.toXMLWithoutData());
            }
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Feed#addData(Pachube.Data)
     */
    public void addData(Data d) {
        this.data.add(d);
    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Feed#getId()
     */
    public int getId() {
        return this.id;
    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Feed#setId(int)
     */
    public void setId(int id) {
        this.id = id;
    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Feed#setId(java.lang.String)
     */
    public void setId(String id) {
        try {
            this.id = Integer.parseInt(id);
        } catch (Exception e) {

        }

    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Feed#getTitle()
     */
    public String getTitle() {
        return this.title;
    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Feed#setTitle(java.lang.String)
     */
    public void setTitle(String title) throws PachubeException {
        this.title = title;
        update();
    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Feed#getUpdated()
     */
    public String getUpdated() {
        return this.updated;
    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Feed#setUpdated(java.lang.String)
     */
    public void setUpdated(String updated) {
        this.updated = updated;
    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Feed#getFeed()
     */
    public URL getFeed() {
        return this.feed;
    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Feed#setFeed(java.net.URL)
     */
    public void setFeed(URL feed) {
        this.feed = feed;
    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Feed#getStatus()
     */
    public Status getStatus() {
        return this.status;
    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Feed#setStatus(Pachube.Status)
     */
    public void setStatus(Status status) throws PachubeException {
        this.status = status;
        update();
    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Feed#getDescription()
     */
    public String getDescription() {
        return this.description;
    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Feed#setDescription(java.lang.String)
     */
    public void setDescription(String description) throws PachubeException {
        this.description = description;
        update();
    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Feed#getWebsite()
     */
    public URL getWebsite() {
        return this.website;
    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Feed#setWebsite(java.net.URL)
     */
    public void setWebsite(URL website) throws PachubeException {
        this.website = website;
        update();
    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Feed#getEmail()
     */
    public String getEmail() {
        return this.email;
    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Feed#setEmail(java.lang.String)
     */
    public void setEmail(String email) throws PachubeException {
        this.email = email;
        update();
    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Feed#getLocation()
     */
    public Location getLocation() {
        return this.location;
    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Feed#setLocation(Pachube.Location)
     */
    public void setLocation(Location location) throws PachubeException {
        this.location = location;
        update();
    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Feed#getData()
     */
    public ArrayList<Data> getData() {
        return this.data;
    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Feed#setData(java.util.ArrayList)
     */
    public void setData(ArrayList<Data> data) {
        this.data = data;
    }

    /**
     * Produces eeml of this feed without any datastream information.
     * 
     * @return String of well formed eeml
     */
    private String toXMLWithoutData() {
        String ret = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<eeml xmlns=\"http://www.eeml.org/xsd/005\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" version=\"5\" xsi:schemaLocation=\"http://www.eeml.org/xsd/005 http://www.eeml.org/xsd/005/005.xsd\">";

        ret = ret + "\n\t<environment ";
        if (this.updated != null) {
            ret = ret + "updated=\"" + this.updated + "\" ";
        }

        if (this.id != null) {
            ret = ret + "id=\"" + this.id + "\"";
        }

        ret = ret + ">\n\t<title>" + this.title + "</title>\n\t";
        ret = ret + "<feed>" + this.feed + "</feed>\n\t";
        ret = ret + "<status>" + this.status + "</status>\n\t";
        ret = ret + "<description>" + this.description + "</description>\n\t";
        ret = ret + "<website>" + this.website + "</website>\n\t";
        ret = ret + this.location.toXML() + "\n\t";

        ret = ret + "</environment>\n</eeml>";

        return ret;

    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Feed#toXML()
     */
    public String toXML() {
        String ret = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<eeml xmlns=\"http://www.eeml.org/xsd/005\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" version=\"5\" xsi:schemaLocation=\"http://www.eeml.org/xsd/005 http://www.eeml.org/xsd/005/005.xsd\">";

        ret = ret + "\n\t<environment ";
        if (this.updated != null) {
            ret = ret + "updated=\"" + this.updated + "\" ";
        }

        if (this.id != null) {
            ret = ret + "id=\"" + this.id + "\"";
        }

        ret = ret + ">\n\t<title>" + this.title + "</title>\n\t";
        ret = ret + "<feed>" + this.feed + "</feed>\n\t";
        ret = ret + "<status>" + this.status + "</status>\n\t";
        ret = ret + "<description>" + this.description + "</description>\n\t";
        ret = ret + "<website>" + this.website + "</website>\n\t";
        if (this.location != null) {
            ret = ret + this.location.toXML() + "\n\t";
        }

        for (int i = 0; i < this.data.size(); i++) {
            if (i == this.data.size() - 1) {
                ret = ret + this.data.get(i).toXML() + "\n";
            } else {
                ret = ret + this.data.get(i).toXML() + "\n\t";
            }
        }

        ret = ret + "</environment>\n</eeml>";

        return ret;

    }

    /*
     * (non-Javadoc)
     * 
     * @see java.lang.Object#toString()
     */
    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Feed#toString()
     */
    @Override
    public String toString() {
        return "Feed [data=" + this.data + ", description=" + this.description
                + ", email=" + this.email + ", feed=" + this.feed + ", id="
                + this.id + ", location=" + this.location + ", status="
                + this.status + ", title=" + this.title + ", updated="
                + this.updated + ", website=" + this.website + "]";
    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Feed#setCreated(boolean)
     */
    public void setCreated(boolean Created) {
        if (Created) {
            this.Created = Created;
        }
    }

}
